package com.yh.hljapp.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yh.hljapp.AppConfig;
import com.yh.hljapp.AppContext;
import com.yh.hljapp.R;
import com.yh.hljapp.api.ErrorHandler;
import com.yh.hljapp.api.RetrofitSingleton;
import com.yh.hljapp.base.BaseFragment;
import com.yh.hljapp.common.FullyLinearLayoutManager;
import com.yh.hljapp.common.MyScrollview;
import com.yh.hljapp.common.PLog;
import com.yh.hljapp.common.StringUtils;
import com.yh.hljapp.common.TDevice;
import com.yh.hljapp.common.UIHelper;
import com.yh.hljapp.gddb.gbmanager.AddSale_Manager;
import com.yh.hljapp.gddb.gdbean.AddBack_HeadBean;
import com.yh.hljapp.gddb.gdbean.AddSaleInt_bodyBean;
import com.yh.hljapp.gddb.gdbean.Add_Sync_Bean;
import com.yh.hljapp.gddb.gdbean.Add_body_Bean;
import com.yh.hljapp.modules.adatper.Add_Sale_Adapter;
import com.yh.hljapp.modules.bean.AddDBD_HB_Bean;
import com.yh.hljapp.modules.bean.AddDBD_Head_Bean;
import com.yh.hljapp.modules.bean.CM;
import com.yh.hljapp.modules.bean.CustPhone;
import com.yh.hljapp.modules.bean.Result;
import com.yh.hljapp.modules.bean.SimpleBackPage;
import com.yh.hljapp.modules.bean.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yh.hljapp.AppConfig.SCN_CUST_ACTION_SCODE;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：zhanghang
 * <p>
 * 工程：hlj
 * <p>
 * 文件名：DBDStockFragment
 * <p>
 * 创建时间：2017.07.31.15:01
 */

public class DBDStockFragment extends BaseFragment implements Add_Sale_Adapter.OnSaleAddAdapterListern {


    @InjectView(R.id.tv_department)
    TextView tvDepartment;
    @InjectView(R.id.ll_department)
    LinearLayout llDepartment;
    @InjectView(R.id.tv_zdr)
    TextView tvZdr;
    @InjectView(R.id.ll_zdr)
    LinearLayout llZdr;
    @InjectView(R.id.tv_ys)
    TextView tvYs;
    @InjectView(R.id.ll_ys)
    LinearLayout llYs;
    @InjectView(R.id.tv_bg)
    TextView tvBg;
    @InjectView(R.id.ll_bg)
    LinearLayout llBg;
    @InjectView(R.id.tv_ywy)
    TextView tvYwy;
    @InjectView(R.id.ll_ywy)
    LinearLayout llYwy;
    @InjectView(R.id.tv_yStock)
    TextView tvYStock;
    @InjectView(R.id.ll_yStock)
    LinearLayout llYStock;
    @InjectView(R.id.tv_target_stock)
    TextView tvTargetStock;
    @InjectView(R.id.ll_target_stock)
    LinearLayout llTargetStock;
    @InjectView(R.id.recyclerview)
    RecyclerView mRecycleview;
    @InjectView(R.id.scrollview)
    MyScrollview scrollView;

    private Add_Sale_Adapter mAdapter;
    ArrayList<Add_body_Bean> checkedCKS;
    private AddDBD_Head_Bean mDBD_head_bean;
    private int position;
    private boolean isSave;
    private User mUser;
    private String mDBDtvTargetStocks;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                JSONObject jo = null;
                try {
                    jo = new JSONObject(message);
                    final String fBase = jo.optString("FBase");
                    final String fWeight = jo.optString("FWeight");

                    User currentUser = AppContext.getInstance().getCurrentUser();
                    if (currentUser == null) {
                        Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户为空，请重新登陆", Snackbar.LENGTH_SHORT).show();
                    } else {
                        handleOtherText(fBase, fWeight);
                    }
                } catch (JSONException e) {
                    Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描正确二维码!", Snackbar.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }
    };


    private void handleOtherText(String text, String fWeight) {
        //先去判断扫描的单号是否存在
        boolean matExist = AddSale_Manager.getInstance(mActivity).isMatExist(text);
        if (matExist) {//存在
            onlyMatInsert(text, fWeight);
        } else {//不存在
            Snackbar.make(mActivity.getWindow().getDecorView(), "出库单不匹配，请重新扫描或同步数据！", Snackbar.LENGTH_SHORT).show();
        }
    }

    public int getHeight(View view) {// 获得某组件的高度
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        return view.getMeasuredHeight();
    }

    private void onlyMatInsert(String barcode, String fWeight) {
        //先判断已添加的中是否存在
        List<Add_body_Bean> listMatBean = mAdapter.getBackList();
        for (int i = 0; i < listMatBean.size(); i++) {
            Add_body_Bean addSyncBean = listMatBean.get(i);
            String id = addSyncBean.getFBillNum();
            //判断是否添加一样
            if (barcode.equals(id)) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "请确认该产品是否已经添加！", Snackbar.LENGTH_SHORT).show();
                return;
            }
        }
        //设置数据
        Add_Sync_Bean matById = AddSale_Manager.getInstance(mActivity).getMatById(barcode);
        Add_body_Bean addSyncBean = new Add_body_Bean();

        addSyncBean.setUnit_id(matById.getUnit_id());
        addSyncBean.setId(matById.getId());
        addSyncBean.setCount(fWeight);
        addSyncBean.setModel(matById.getModel());
        addSyncBean.setName(matById.getName());
        addSyncBean.setNumber(matById.getNumber());
        addSyncBean.setUnitgroup_name(matById.getUnitgroup_name());
        addSyncBean.setUnit_name(matById.getUnit_name());
        addSyncBean.setDefunitId(matById.getDefunitId());
        addSyncBean.setBaseName(matById.getBaseName());
        addSyncBean.setBaseunit(matById.getBaseunit());
        addSyncBean.setUnitgroup_id(matById.getUnitgroup_id());
        String fOutStockName = mDBD_head_bean.getFOutStockName();
        if (fOutStockName!=null){
            addSyncBean.setFDCStockName(mDBD_head_bean.getFOutStockName());
        } else {
            addSyncBean.setFDCStockName(mDBDtvTargetStocks);
        }
        addSyncBean.setFDCStockID(mDBD_head_bean.getFOutStock());

        checkedCKS.add(addSyncBean);

        mAdapter = new Add_Sale_Adapter(mActivity, checkedCKS, this);
        mRecycleview.setAdapter(mAdapter);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_dbd, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }


    @Override
    public void initView(View view) {
        super.initView(view);
        TDevice.hideSoftKeyboard(mActivity);
        setHasOptionsMenu(true);
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
        isSave = false;
        llDepartment.setOnClickListener(this);
        llZdr.setOnClickListener(this);
        llYs.setOnClickListener(this);
        llBg.setOnClickListener(this);
        llYwy.setOnClickListener(this);
        llYStock.setOnClickListener(this);
        llTargetStock.setOnClickListener(this);
        checkedCKS = new ArrayList<>();

        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(getContext());
        mRecycleview.setNestedScrollingEnabled(false);
        mAdapter = new Add_Sale_Adapter(mActivity, checkedCKS, this);
        mRecycleview.setLayoutManager(linearLayoutManager);
    }

    @Override
    public void initData() {
        super.initData();
        mUser = AppContext.getInstance().getCurrentUser();
        mDBD_head_bean = new AddDBD_Head_Bean();
          //text
        String DBDtvDepartments = AppContext.getInstance().getProperty("DBDtvDepartment");
        String DBDtvYss = AppContext.getInstance().getProperty("DBDtvYs");
        String DBDtvBgs = AppContext.getInstance().getProperty("DBDtvBg");
        String DBDtvYwys = AppContext.getInstance().getProperty("DBDtvYwy");
        String DBDtvYStocks = AppContext.getInstance().getProperty("DBDtvYStock");
        mDBDtvTargetStocks = AppContext.getInstance().getProperty("DBDtvTargetStock");
        //id
        String DBDtvDepartments_id = AppContext.getInstance().getProperty("DBDtvDepartment_id");
        String DBDtvYss_id = AppContext.getInstance().getProperty("DBDtvYs_id");
        String DBDtvBgs_id = AppContext.getInstance().getProperty("DBDtvBg_id");
        String DBDtvYwys_id = AppContext.getInstance().getProperty("DBDtvYwy_id");
        String DBDtvYStocks_id = AppContext.getInstance().getProperty("DBDtvYStock_id");
        String DBDtvTargetStocks_id = AppContext.getInstance().getProperty("DBDtvTargetStock_id");

        if (!StringUtils.isEmpty(DBDtvDepartments) && !StringUtils.isEmpty(DBDtvYss) && !StringUtils.isEmpty(DBDtvBgs)
                && !StringUtils.isEmpty(DBDtvYwys) && !StringUtils.isEmpty(DBDtvYStocks)
                && !StringUtils.isEmpty(mDBDtvTargetStocks)) {

            tvDepartment.setText(DBDtvDepartments);
            tvYs.setText(DBDtvYss);
            tvBg.setText(DBDtvBgs);
            tvYwy.setText(DBDtvYwys);
            tvYStock.setText(DBDtvYStocks);
            tvTargetStock.setText(mDBDtvTargetStocks);

            mDBD_head_bean.setFDeptId(DBDtvDepartments_id);
            mDBD_head_bean.setFYUser(DBDtvYss_id);
            mDBD_head_bean.setFBUser(DBDtvBgs_id);
            mDBD_head_bean.setFPUser(DBDtvYwys_id);
            mDBD_head_bean.setFInStock(DBDtvYStocks_id);
            mDBD_head_bean.setFOutStock(DBDtvTargetStocks_id);
        }

        mAdapter = new Add_Sale_Adapter(mActivity, checkedCKS, this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ll_department:
                bundle.putString("type", "bm");
                UIHelper.showSimpleBackForResult(this, mActivity, 1, SimpleBackPage.CUST_PHEON, bundle, "部门");
                break;
            case R.id.ll_zdr:
                bundle.putString("type", "zdr");
                UIHelper.showSimpleBackForResult(this, mActivity, 2, SimpleBackPage.CUST_PHEON, bundle, "制单人");
                break;
            case R.id.ll_ys:
                bundle.putString("type", "ys");
                UIHelper.showSimpleBackForResult(this, mActivity, 3, SimpleBackPage.CUST_PHEON, bundle, "验收");
                break;
            case R.id.ll_bg:
                bundle.putString("type", "bg");
                UIHelper.showSimpleBackForResult(this, mActivity, 4, SimpleBackPage.CUST_PHEON, bundle, "保管");
                break;
            case R.id.ll_ywy:
                bundle.putString("type", "ywy");
                UIHelper.showSimpleBackForResult(this, mActivity, 5, SimpleBackPage.CUST_PHEON, bundle, "业务员");
                break;
            case R.id.ll_yStock:
                bundle.putString("type", "drck");
                UIHelper.showSimpleBackForResult(this, mActivity, 6, SimpleBackPage.CUST_PHEON, bundle, "调入仓库");
                break;
            case R.id.ll_target_stock:
                bundle.putString("type", "dcck");
                UIHelper.showSimpleBackForResult(this, mActivity, 7, SimpleBackPage.CUST_PHEON, bundle, "调出仓库");
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            final CustPhone item = (CustPhone) data.getSerializableExtra("item");
            if (item != null) {
                String name = item.getName();
                String id = item.getId();
                switch (requestCode) {
                    case 1:
                        tvDepartment.setText(name);
                        mDBD_head_bean.setFDeptIdName(name);
                        mDBD_head_bean.setFDeptId(id);
                        AppContext.getInstance().setProperty("DBDtvDepartment", name);
                        AppContext.getInstance().setProperty("DBDtvDepartment_id", id);
                        break;
                    case 3:
                        tvYs.setText(name);
                        mDBD_head_bean.setFYUserName(name);
                        mDBD_head_bean.setFYUser(id);
                        AppContext.getInstance().setProperty("DBDtvYs", name);
                        AppContext.getInstance().setProperty("DBDtvYs_id", id);
                        break;
                    case 4:
                        tvBg.setText(name);
                        mDBD_head_bean.setFBUserName(name);
                        mDBD_head_bean.setFBUser(id);
                        AppContext.getInstance().setProperty("DBDtvBg", name);
                        AppContext.getInstance().setProperty("DBDtvBg_id", id);
                        break;
                    case 5:
                        tvYwy.setText(name);
                        mDBD_head_bean.setFPUserName(name);
                        mDBD_head_bean.setFPUser(id);
                        AppContext.getInstance().setProperty("DBDtvYwy", name);
                        AppContext.getInstance().setProperty("DBDtvYwy_id", id);
                        break;
                    case 6:
                        tvYStock.setText(name);
                        mDBD_head_bean.setFInStockName(name);
                        mDBD_head_bean.setFInStock(id);
                        AppContext.getInstance().setProperty("DBDtvYStock", name);
                        AppContext.getInstance().setProperty("DBDtvYStock_id", id);
                        break;
                    case 7:
                        tvTargetStock.setText(name);
                        mDBD_head_bean.setFOutStockName(name);
                        mDBD_head_bean.setFOutStock(id);
                        AppContext.getInstance().setProperty("DBDtvTargetStock", name);
                        AppContext.getInstance().setProperty("DBDtvTargetStock_id", id);
                        break;
                    case 8://adapter中点击发货仓库 自选的仓库
                        ArrayList<Add_body_Bean> backList = mAdapter.getBackList();
                        Add_body_Bean backMatBean = backList.get(position);
                        backMatBean.setTDCStockID(item.getId());
                        backMatBean.setTDCStockName(item.getName());
                        backList.set(position, backMatBean);
                        mAdapter.setBackList(backList);
                        mAdapter.notifyItemChanged(position);
                        break;

                }
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_add_mat, menu);
        MenuItem item = menu.getItem(0);
        item.setVisible(false);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                subMat();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private void subMat() {
        ArrayList<Add_body_Bean> addSyncBeen_List = mAdapter.getBackList();
        if (addSyncBeen_List == null || addSyncBeen_List.size() == 0) {
            Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描物料，再提交", Snackbar.LENGTH_SHORT).show();
            return;
        }
        //表头
        String fDeptId = mDBD_head_bean.getFDeptId();
        String fyUser = mDBD_head_bean.getFYUser();
        String fbUser = mDBD_head_bean.getFBUser();
        String fpUser = mDBD_head_bean.getFPUser();
        String fInStock = mDBD_head_bean.getFInStock();
        String fOutStock = mDBD_head_bean.getFOutStock();

        if (mUser != null) {
            String id = mUser.getId();
            mDBD_head_bean.setFUser(id);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户获取失败，请重新登陆！", Snackbar.LENGTH_SHORT).show();
        }

        if (!StringUtils.isEmpty(fDeptId) && !StringUtils.isEmpty(fInStock) && !StringUtils.isEmpty(fOutStock)) {

            mDBD_head_bean.setFDeptId(fDeptId);
            mDBD_head_bean.setFOutStock(fOutStock);
            mDBD_head_bean.setFInStock(fInStock);
            mDBD_head_bean.setFYUser(fyUser);
            mDBD_head_bean.setFBUser(fbUser);
            mDBD_head_bean.setFPUser(fpUser);

            //表体
            List<AddSaleInt_bodyBean> bodys = new ArrayList<>();
            for (int i = 0; i < addSyncBeen_List.size(); i++) {
                AddSaleInt_bodyBean bodyBean = new AddSaleInt_bodyBean();
                Add_body_Bean addSyncBeans = addSyncBeen_List.get(i);

                String fCount = addSyncBeans.getCount();
                if (fCount.contains(".")) {
                    String counts = fCount.substring(0, fCount.indexOf("."));
                    bodyBean.setFQty(counts);
                } else {
                    bodyBean.setFQty(fCount);
                }
                String unit_id = addSyncBeans.getUnit_id();
                String fdcStockID = addSyncBeans.getTDCStockID();  //表体id
                String id = addSyncBeans.getId();

                if (!StringUtils.isEmpty(fdcStockID)) {
                    bodyBean.setFStockId(fdcStockID);
                } else if (!StringUtils.isEmpty(fOutStock)) {
                    bodyBean.setFStockId(fOutStock);
                } else {
                    bodyBean.setFStockId("0");
                }

                bodyBean.setFUnitId(unit_id);
                bodyBean.setFProductID(id);

                bodys.add(bodyBean);
            }

            showWaitDialog();
            AddDBD_HB_Bean addSaleIntHbBean = new AddDBD_HB_Bean();
            addSaleIntHbBean.setBodyList(bodys);
            addSaleIntHbBean.setHeadDetail(mDBD_head_bean);

            Gson gson = new Gson();
            String json = gson.toJson(addSaleIntHbBean);
            String token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
            CM cm = new CM();
            cm.setToken(token);
            cm.setData(json);
            RetrofitSingleton.getApiService(mActivity).
                    StockAllotSubmit(cm)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "必填信息不能为空！", Snackbar.LENGTH_SHORT).show();
        }

    }

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "提交成功!", Snackbar.LENGTH_SHORT).show();

                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mActivity.finish();
                        Bundle bundle = new Bundle();
                        UIHelper.showSimpleBack(mActivity, SimpleBackPage.DBD, bundle, "调拨单");
                    }
                }, 1000);//3秒后执行Runnable中的run方法
//                mActivity.finish();
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), result.getMessage(), Snackbar.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }
        ButterKnife.reset(this);
    }

    @Override
    public void onFHCKClick(Add_body_Bean bean, int position) {
        this.position = position;
        Bundle bundle = new Bundle();
        bundle.putString("type", "fhck");
        UIHelper.showSimpleBackForResult(this, mActivity, 8, SimpleBackPage.CUST_PHEON, bundle, "发货仓库");
    }

    @Override
    public void onDeleted(Add_body_Bean bean, int position) {

    }


}
